import axios from 'axios';
import { Toast } from 'antd-mobile';
import store from '../store';
import { loginStatusActionCreate } from '../store/action/action';

window.ywxConfig = {
  api: ''
}

let utils = {

  request({
    formDataFormat,
    method = 'get',
    headers,
    ...other
  }) {

    let data = other.data;
    let formData;
    if (formDataFormat && data && method === 'post') {
      formData = new FormData();
      for (let key in data) {
        formData.append(key, data[key]);
      }
      other.data = formData;
    }

    let promise = new Promise((resolve, reject) => {
      axios({
        method,
        baseURL: window.ywxConfig.api,
        headers: headers,
        withCredentials: true,
        ...other
      }).then(res => {
        if (res.data.code === '1') {
          resolve(res.data.data)
        } else {
          if (res.data.msg) {
            Toast.fail(res.data.msg)
          }
          reject(res.data);
        }
      }).catch(err => {
        if (err.response && err.response.status === 401) {
          store.dispatch(loginStatusActionCreate(true));
        }
      })
    });

    return promise
  },

  arrived(options) {
    options.offset = options.offset || 0;
    let scrollListener = function () {
      //let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
      //let top = options.el.offsetTop;
      let height = document.documentElement.clientHeight || document.body.clientHeight;
      let positionY = options.el.getBoundingClientRect().top;
      if (positionY + options.offset <= height) {
        options.listener()
      }
    }

    window.addEventListener('scroll', scrollListener);
    return scrollListener;
  },

  validatePhone(phone) {
    return /^1\d{10}$/.test(phone)
  },

  throttle(method, duration) {
    let begin = 0;
    return function () {
      let context = this,
        args = arguments,
        current = new Date();
      if (current - begin >= duration) {
        method.apply(context, args);
        begin = current;
      }
    }
  },

  formatTime(timeString) {
    timeString = timeString.replace('年', "/");
    timeString = timeString.replace('月', "/");
    timeString = timeString.replace('日', " ");

    let time = new Date(timeString);

    let year = time.getFullYear();
    let month = time.getMonth() + 1;
    month = '' + month >= 10 ? month : '0' + month;

    let day = time.getDate();
    day = '' + day >= 10 ? day : '0' + day;

    let hour = time.getHours();
    hour = '' + hour >= 10 ? hour : '0' + hour;

    let minutes = time.getMinutes();
    minutes = '' + minutes >= 10 ? minutes : '0' + minutes;

    let seconds = time.getSeconds();
    seconds = '' + seconds >= 10 ? seconds : '0' + seconds;

    return {
      year,
      month,
      day,
      hour,
      minutes,
      seconds
    }
  },

  rem2px(rem) {
    return window.document.documentElement.clientWidth / 7.5 * rem
  },

  innerHeight() {
    return window.innerHeight || document.documentElement.clientHeight || 0
  },

  handleImgUrl(url) {
    return window.config.imgBaseUrl + url;
  },


  formatLimitTime(timestamp) {

    timestamp = parseInt(timestamp / 1000);

    let hour = parseInt(timestamp / 3600);
    hour = (hour >= 10 ? '' : '0') + hour;

    let minutes = parseInt((timestamp % 3600) / 60);
    minutes = (minutes >= 10 ? '' : '0') + minutes;


    let seconds = timestamp % 60;
    seconds = (seconds >= 10 ? '' : '0') + seconds;


    return {
      hour,
      minutes,
      seconds
    }

  },

  getUrlQuery(query) {
    var arr = window.location.search.slice(1).split('&');
    var obj = {};
    arr.forEach(function (v) {
      var value = v.split('=');
      obj[value[0]] = value[1];
    });
    if (typeof (query) == 'string') {
      return obj[query];
    }
    return obj
  }

};

export default utils;